package com.isunland.managesystem.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.View;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.RDeviceListAdapter;
import com.isunland.managesystem.base.BaseMultiChoiceAdapter;
import com.isunland.managesystem.base.BaseMultiSearchListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.RDeviceList;
import com.isunland.managesystem.entity.RDeviceListListOriginal;
import com.isunland.managesystem.utils.LocalSearch;
import com.isunland.managesystem.utils.MyStringUtil;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/3/24 17:45
 */

public class RDeviceListListFragment extends BaseMultiSearchListFragment<RDeviceList> {

  public static final String EXTRA_NAMES =
      "com.isunland.managesystem.uiRDeviceListListFragment.EXTRA_NAMES";
  public static final String EXTRA_NOS =
      "com.isunland.managesystem.uiRDeviceListListFragment.EXTRA_NOS";

  public static Fragment newInstance(String nos) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_NOS, nos);
    RDeviceListListFragment fragment = new RDeviceListListFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setTitleCustom(R.string.selectDevice);
  }

  @Override protected String[] setQueryField() {
    return new String[] { "deviceName", "deviceIdentNo" };
  }

  @NonNull @Override protected BaseMultiChoiceAdapter initAdapter() {
    HashMap<RDeviceList, Boolean> map = new HashMap<>();
    if (getArguments() != null) {
      String nos = getArguments().getString(EXTRA_NOS);
      map = LocalSearch.getSelectMap(nos, mListOriginal, "deviceIdentNo");
    }
    return new RDeviceListAdapter(getActivity(), mList, map);
  }

  @NonNull @Override protected Intent getSelectIntent(ArrayList<RDeviceList> list) {

    Intent i = new Intent();
    String namesStr = MyStringUtil.joinStr(list, "deviceName", MyStringUtil.COMMA);
    String nosStr = MyStringUtil.joinStr(list, "deviceIdentNo", MyStringUtil.COMMA);
    i.putExtra(EXTRA_NAMES, namesStr);
    i.putExtra(EXTRA_NOS, nosStr);
    return i;
  }

  @Override public String getUrl() {
    return ApiConst.URL_QUERY_LIST_DEVICE;
  }

  @Override public void resolveResponse(String json) {
    RDeviceListListOriginal original = new Gson().fromJson(json, RDeviceListListOriginal.class);
    ArrayList<RDeviceList> rows = original.getRows();
    mListOriginal.clear();
    mList.clear();
    mListTemp.clear();

    mListOriginal.addAll(rows);
    mList.addAll(rows);
    mListTemp.addAll(rows);
    setAdapter();
  }
}
